import React, { Component } from 'react';
import { connect } from 'dva';
import {
    Spin,
    Button,
    message,
    Card,
    Table,
    Row,
    Col,
    Tooltip,
    Form,
    Input,
    Popconfirm,
    Select,
    DatePicker
} from 'antd';
import {PageHeaderWrapper} from "@ant-design/pro-layout";
import { FormattedMessage } from 'umi/locale';
import APP from "@/components/Tool/BaseAPP";
import moment from "moment";
import router from 'umi/router';
const {RangePicker} = DatePicker;
/**
 * 分页参数
 * @Author 肖家添
 * @Date 2019/8/22 15:09
 */
let pagingData = {
    _pageSize: 10,
    _current: 1,
    _total: 0,
};

@connect(({ journalModel }) => ({
    journalModel
}))
@Form.create()
class journal extends Component {
    state = {
        loading: false,
        pageDataSource: [],
        selectedKeys: [],
        selectedRows: []
    };

    componentDidMount() {
        this.findPageDataSource();
    }

    findPageDataSource = (e) => {
        let that = this, params = {...pagingData};
        if(e){
            pagingData._current = 1;
            e.preventDefault();
        }
        const { form } = this.props;
        form.validateFieldsAndScroll((err, values) => {
            APP.validNilParams(values);
            params = {...params, ...values};
            const area = params.area;
            if(area){
                delete params.area;
                if(area.length >= 1){
                    params.houseProvinceId = area[0];
                }
                if(area.length >= 2){
                    params.houseCityId = area[1];
                }
                if(area.length >= 3){
                    params.houseAreaId = area[2];
                }
            }
            const createTime = params.createTime;
            if (createTime) {
                params.createTimeStart = createTime[0].format('YYYY-MM-DD');
                params.createTimeEnd = createTime[1].format('YYYY-MM-DD');
                delete params.createTime;
            }
            requestContinue();
        });
        function requestContinue(){
            const { dispatch } = that.props;
            APP.loading(that);
            dispatch({
                type: "journalModel/list",
                payload: params,
                callback: function(data){
                    APP.closeLoading(that);
                    if(data.success){
                        const { list, pagination } = data.datas;
                        pagingData._current = pagination.current;
                        pagingData._pageSize = pagination.pageSize;
                        pagingData._total = pagination.total;
                        that.setState({
                            pageDataSource: list,
                            selectedKeys: [],
                            selectedRows: []
                        });
                    }
                }
            });
        }
    };

    getDataById = (journalId = null) => {
        let fromList = 'look';
        if (!APP.isValidObj(journalId)) {
            const { selectedKeys, selectedRows } = this.state;
            if(selectedKeys.length !== 1) return;
            journalId = selectedKeys[0];
            fromList = 'edit';
        }
        router.push({
            pathname: '/journal/editJournal',
            state: {id: journalId,fromList:fromList}
        });
    };

    enabledControl = (isEnabled) => {
        const { selectedKeys, selectedRows } = this.state;
        if(selectedKeys <= 0) return;
        const that = this, { dispatch } = this.props;
        if(isEnabled == -1 && selectedRows[0]["isenabled"] == "可用"){
          message.error("当前期刊已经上架，不可删除！");
          return;
        }
        APP.loading(that);
        dispatch({
            type: "journalModel/enabledControl",
            payload: {
                ids: selectedKeys.join(","),
                isEnabled: isEnabled
            },
            callback: function(data){
                APP.closeLoading(that);
                if(data.success){
                    message.success("操作成功");
                    that.findPageDataSource();
                }else{
                    message.error("操作失败！");
                }
            }
        });
    };

    xstatusControl = (xstatus) => {
        const { selectedKeys, selectedRows } = this.state;
        if(selectedKeys <= 0) return;
        const that = this, { dispatch } = this.props;
        APP.loading(that);
        if (xstatus === 3) {
            for (let i = 0;i < selectedRows.length;i++) {
                if (selectedRows[i].countPoint === 0) {
                    message.error("每个期刊必须关联一个点位");
                    APP.closeLoading(that);
                    return;
                }
            }
        }
        dispatch({
            type: "journalModel/xstatusControl",
            payload: {
                ids: selectedKeys.join(","),
                xstatus: xstatus
            },
            callback: function(data){
                APP.closeLoading(that);
                if(data.success){
                    message.success("操作成功");
                    that.findPageDataSource();
                }else{
                    message.error("操作失败！");
                }
            }
        });
    };

    exportData = (type) => {
        APP.exportData({
            parent: this,
            requestUrl: "/api/journal/exportData",
            fileNamePrefix: "期刊",
            exportType: type,
            tablePagination: pagingData
        });
    };

    render() {
        const {
            loading,
            pageDataSource,
            selectedKeys
        } = this.state;
        const { form } = this.props;
        const that = this;
        const { getFieldDecorator } = form;
        /**
         * 表格选中事件
         * @Author 肖家添
         * @Date 2019/8/19 19:15
         */
        const rowSelection = {
            selectedRowKeys: selectedKeys,
            onChange: selectedRowKeys => {
                that.setState({ selectedKeys: selectedRowKeys });
            },
        };
        /**
         * 按钮样式
         * @Author 肖家添
         * @Date 2019/8/19 19:42
         */
        const buttonsStyle = {
            style: {
                marginRight: '15px',
            },
        };

        return (
            <Spin spinning={loading}>
                <PageHeaderWrapper title={<FormattedMessage id="menu.journal.journal"/>}>
                    <Card style={{marginBottom: 15}}>
                        <Form layout="inline" onSubmit={this.findPageDataSource}>
                            <Row>
                                <Col span={8}>
                                    <Form.Item label="客户名称">
                                        {getFieldDecorator('customerName', {})(<Input placeholder={"请输入客户名称"} allowClear={true} />)}
                                    </Form.Item>
                                </Col>
                                <Col span={8}>
                                    <Form.Item label="广告名称">
                                        {getFieldDecorator('aname', {})(<Input placeholder={"请输入广告名称"} allowClear={true} />)}
                                    </Form.Item>
                                </Col>
                                <Col span={8}>
                                    <Form.Item label="审核状态">
                                        {getFieldDecorator('xstatus', {})(
                                            <Select placeholder={"请选择状态"} allowClear={true} style={{width: 174}}>
                                                <Select.Option value={3}>发布</Select.Option>
                                                <Select.Option value={1}>待审核</Select.Option>
                                            </Select>
                                        )}
                                    </Form.Item>
                                </Col>
                                <Col span={8}>
                                    <Form.Item label="期刊状态">
                                        {getFieldDecorator('isenabled', {})(
                                            <Select placeholder={"请选择状态"} allowClear={true} style={{width: 174}}>
                                                <Select.Option value={1}>上架</Select.Option>
                                                <Select.Option value={0}>下架</Select.Option>
                                            </Select>
                                        )}
                                    </Form.Item>
                                </Col>
                                <Col span={8}>
                                    <Form.Item label='点位机器串码'>
                                        {getFieldDecorator('imei', {})(<Input placeholder={'请输入点位机器串码'} allowClear={true} />)}
                                    </Form.Item>
                                </Col>
                                <Col span={8}>
                                    <Form.Item label={'创建时间'}>
                                        {getFieldDecorator('createTime', {})(<RangePicker />)}
                                    </Form.Item>
                                </Col>
                                <Col span={8}>
                                    <Form.Item label="广告类型">
                                        {getFieldDecorator('atype', {})(
                                            <Select placeholder={"请选择广告类型"} allowClear={true} style={{width: 174}}>
                                                <Select.Option value={1}>视频</Select.Option>
                                                <Select.Option value={2}>图片</Select.Option>
                                                <Select.Option value={3}>文字</Select.Option>
                                                {/*<Select.Option value={4}>其他</Select.Option>*/}
                                            </Select>
                                        )}
                                    </Form.Item>
                                </Col>
                            </Row>
                            <Row>
                                <Col style={{ textAlign: 'center', height: '32px', lineHeight: '32px', marginTop: 20 }}>
                                    <Button type="primary" htmlType="submit" {...APP.buttonsStyle_MR15}>
                                        查找
                                    </Button>
                                    <Button type="primary" {...APP.buttonsStyle_MR15} onClick={() => this.exportData(1)}>
                                        导出本页
                                    </Button>
                                    <Button type="primary" {...APP.buttonsStyle_MR15} onClick={() => this.exportData(2)}>
                                        导出所有
                                    </Button>
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <Card style={{marginBottom: 15}}>
                        <Button type="primary" {...buttonsStyle} onClick={() => {
                            router.push({
                                pathname: '/journal/editJournal',
                                state: {fromList:'add'}
                            });
                        }}>
                            新增
                        </Button>
                        <Tooltip title={selectedKeys.length === 1 ? '' : '请选中一行数据'}>
                            <Button type="primary" {...buttonsStyle} onClick={() => this.getDataById()}>
                                编辑
                            </Button>
                        </Tooltip>
                        <Tooltip title={selectedKeys.length > 0 ? '' : '请选中数据'}>
                            <Button type="primary" {...buttonsStyle} onClick={() => this.xstatusControl(3)}>
                                发布期刊
                            </Button>
                        </Tooltip>
                        <Tooltip title={selectedKeys.length > 0 ? '' : '请选中数据'}>
                            <Button type="primary" {...buttonsStyle} onClick={() => this.enabledControl(0)}>
                                下架
                            </Button>
                        </Tooltip>
                        <Tooltip title={selectedKeys.length > 0 ? '' : '请选中数据'}>
                            <Popconfirm
                                title="确定删除选中数据吗？"
                                onConfirm={() => this.enabledControl(-1)}
                                okText="删除"
                                cancelText="取消"
                                disabled={!(selectedKeys.length > 0)}
                            >
                                <Button type="primary" {...buttonsStyle}>
                                    删除
                                </Button>
                            </Popconfirm>
                        </Tooltip>
                    </Card>
                    <Card>
                        <Table
                            bordered
                            rowKey={data => `${data.id}`}
                            rowSelection={APP.tableRowSelection(function(selectedRowKeys, selectedRows){
                                that.setState({
                                    selectedKeys: selectedRowKeys,
                                    selectedRows: selectedRows
                                });
                            }, selectedKeys)}
                            columns={this.columns}
                            dataSource={pageDataSource}
                            pagination={{
                                pageSize: pagingData._pageSize,
                                current: pagingData._current,
                                total: pagingData._total,
                                onChange: (page, pageSize) => {
                                    pagingData._current = page;
                                    this.findPageDataSource();
                                },
                                showTotal: total => `共 ${total} 条数据`,
                            }}
                        />
                    </Card>
                </PageHeaderWrapper>
            </Spin>
        );
    }

    columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',
        },
        {
            title: '运营商',
            dataIndex: 'companyName',
            key: 'companyName',
        },
        {
            title: '广告名称',
            dataIndex: 'journalName',
            key: 'journalName',
            render: (text, record) => {
                return <a onClick={() =>{this.getDataById(record.id)}}>{text}</a>;
            }
        },
        {
            title: '行业分类',
            dataIndex: 'gvlistName',
            key: 'gvlistName',
        },
        {
            title: '客户名称',
            dataIndex: 'customerName',
            key: 'customerName',
        },
        {
            title: '广告类型',
            dataIndex: 'journalTypeName',
            key: 'journalTypeName'
        },
        {
            title: '文件大小',
            dataIndex: 'fileSize',
            key: 'fileSize'
        },
        {
            title: '广告过期时间',
            dataIndex: 'expireDate',
            key: 'expireDate',
            render: function(text){
                if(text) return APP.momentFormatToStr(moment(text, 'YYYY-MM-DD'));
                return  "";
            }
        },
        {
            title: '点位机器串码',
            dataIndex: 'imeiGroup',
            key: 'imeiGroup',
            render: (value, record) => {
                if (APP.isValidObj(value)) {
                    const valueArr = value.split(',');
                    if (valueArr.length > 1) {
                        value = valueArr.map(item => (
                            <Row>{item}</Row>
                        ));
                        if (valueArr.length > 3) {
                            value = <div style={{
                                height:'82px',
                                overflow:'scroll'
                            }}>{value}</div>
                        }
                    }
                }
                return (value);
            }
        },
        {
            title: '投放点位数',
            dataIndex: 'countPoint',
            key: 'countPoint'
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime'
        },
        {
            title: '创建人',
            dataIndex: 'creatorName',
            key: 'creatorName'
        },
        {
            title: '审核状态',
            dataIndex: 'xstatus',
            key: 'xstatus'
        },
        {
            title: '期刊状态',
            dataIndex: 'isenabled',
            key: 'isenabled'
        },
        {
            title: '文件MD5',
            dataIndex: 'fileMd5',
            key: 'fileMd5'
        }
    ];
}

export default journal;
